package android.slc.appbase.ui.vd;

import android.slc.appbase.entity.ErrorMsg;
import android.slc.appbase.ui.vd.wrapper.IBaseListWrapper;

import androidx.annotation.NonNull;
import androidx.databinding.Observable;
import androidx.lifecycle.LifecycleOwner;

import java.io.Serializable;
import java.util.List;

/**
 * 基础的单次加载盒子vm
 *
 * @author slc
 * @date 2020-08-25 16:13
 */
public abstract class BaseListVd<T extends Serializable, VB extends BaseListCommonVmBox<T>> extends BaseListCommonVd<T, VB> {

    private final Observable.OnPropertyChangedCallback dataListChangedCallback = new Observable.OnPropertyChangedCallback() {
        @Override
        public void onPropertyChanged(Observable sender, int propertyId) {
            notifyRecyclerRefresh(vmBox.getDataList());
        }
    };

    private final Observable.OnPropertyChangedCallback errorMsgChangedCallback = new Observable.OnPropertyChangedCallback() {
        @Override
        public void onPropertyChanged(Observable sender, int propertyId) {
            notifyRefreshError(vmBox.getErrorMsg());
        }
    };

    private final Observable.OnPropertyChangedCallback startRefreshChangedCallback = new Observable.OnPropertyChangedCallback() {
        @Override
        public void onPropertyChanged(Observable sender, int propertyId) {
            swipeRecycler.setRefreshing(true);
        }
    };

    protected IBaseListWrapper<?> getListPageWrapper() {
        if (vmBox instanceof IBaseListWrapper<?>) {
            return (IBaseListWrapper<?>) vmBox;
        }
        throw new RuntimeException("vmBox没有实现IBaseListWrapper接口");
    }

    @Override
    protected void initMustCondition() {
        super.initMustCondition();
        this.vmBox.getDataListOf().addOnPropertyChangedCallback(dataListChangedCallback);
        this.vmBox.getErrorMsgObservable().addOnPropertyChangedCallback(errorMsgChangedCallback);
        getListPageWrapper().getStartRefreshOf().addOnPropertyChangedCallback(startRefreshChangedCallback);
    }

    protected void notifyRecyclerRefresh(List<T> list) {
        swipeRecycler.refresh();
    }

    protected void notifyRefreshError(ErrorMsg errorMsg) {
        swipeRecycler.refresh();
    }

    @Override
    public void onDestroy(@NonNull LifecycleOwner owner) {
        super.onDestroy(owner);
        this.vmBox.getDataListOf().removeOnPropertyChangedCallback(dataListChangedCallback);
        this.vmBox.getErrorMsgObservable().removeOnPropertyChangedCallback(errorMsgChangedCallback);
        getListPageWrapper().getStartRefreshOf().removeOnPropertyChangedCallback(startRefreshChangedCallback);
    }
}
